import 'package:flutter/material.dart';
import 'package:qunaimedical/components/comment_bar.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_comment.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/components/rounded_network_image.dart';
import 'package:qunaimedical/models/comment.dart';
import 'package:qunaimedical/models/consultation.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/comment_page.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

/// 即时咨询详情界面
class TimelyConsultationDetailPage extends StatefulWidget {
  final Consultation item;

  const TimelyConsultationDetailPage(this.item, {Key key}) : super(key: key);

  @override
  _TimelyConsultationDetailPageState createState() =>
      _TimelyConsultationDetailPageState();
}

class _TimelyConsultationDetailPageState
    extends State<TimelyConsultationDetailPage> {
  /// 图片列表
  List<String> _images = [];
  TextEditingController _commentController = TextEditingController();

  /// 评论列表
  List<Comment> _items = [];

  @override
  void initState() {
    super.initState();
    _images = widget.item.appointmentImag == ''
        ? []
        : widget.item.appointmentImag.split(',');
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('详情'),
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemBuilder: (c, i) {
                  if (i == 0) {
                    return _buildConsultationInfo();
                  } else {
                    return ItemComment(
                      _items[i - 1],
                      onDelete: () {
                        DialogUtils.showAlertDialog(context, '提示', '确认删除这条评论？',
                            onPressed: () {
                          Navigator.pop(context);
                          _delete(i - 1);
                        });
                      },
                      onReply: () {
                        Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (c) =>
                                        CommentPage(item: _items[i - 1])))
                            .then((value) {
                          if (value != null && value) {
                            _fetchData();
                          }
                        });
                      },
                    );
                  }
                },
                itemCount: _items.length + 1,
              ),
            ),
            CommentBar(
              hintText: '评论一下',
              controller: _commentController,
              onSendPressed: _comment,
            ),
          ],
        ));
  }

  /// 创建评论
  void _comment() async {
    CommonUtils.hideKeyboard(context);
    String content = _commentController.text.trim();
    if (SPUtils.getUser() == null) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行登录');
      return;
    }
    if (content.isEmpty) {
      ToastUtil.show('评论内容不能为空', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.COMMENT_ADD, {
      "timelyConsultationId": widget.item.id, // 所评论预约单ID
      "content": content, // 评论内容
      "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
    });
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        _commentController.clear();
        _fetchData();
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  Widget _buildConsultationInfo() {
    var paddingValue = EdgeInsets.only(left: 16, right: 16, bottom: 16);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Offstage(
          child: CustomDivider(),
          offstage: widget.item.title == '',
        ),
        Offstage(
          child: PrimaryLabel('主题'),
          offstage: widget.item.title == '',
        ),
        Offstage(
          offstage: widget.item.title == '',
          child: Container(
            color: Colors.white,
            child: Text(widget.item.title),
            padding: paddingValue,
          ),
        ),
        CustomDivider(),
        PrimaryLabel('症状描述'),
        Container(
          color: Colors.white,
          child: Text(widget.item.content),
          padding: paddingValue,
        ),
        Offstage(
          child: CustomDivider(),
          offstage: _images.isEmpty,
        ),
        Offstage(
          child: PrimaryLabel('图片'),
          offstage: _images.isEmpty,
        ),
        Offstage(
          offstage: _images.isEmpty,
          child: Container(
            color: Colors.white,
            height: 90,
            width: double.maxFinite,
            alignment: Alignment.topLeft,
            padding: paddingValue,
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              itemBuilder: (c, i) {
                return InkWell(
                  onTap: () => CommonUtils.openGallery(context,
                      _images.map((e) => Urls.BASE_URL + e).toList(), i),
                  child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(6)),
                    child:  RoundedNetWorkImage('${Urls.BASE_URL}${_images[i]}'),
                  ),
                );
              },
              itemCount: _images.length,
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(width: 10);
              },
            ),
          ),
        ),
        CustomDivider(),
        PrimaryLabel('评论'),
        Divider(),
      ],
    );
  }

  void _fetchData() async {
    var result = await XHttp.postJson(Urls.COMMENT_LIST, {
      "pageNo": 1, // 起始页（必填）
      "pageSize": 1000, // 分页大小（必填）
      "timelyConsultationId": widget.item.id, // 预约单ID/咨询单ID（必填）
      "doctorId": "" // 暂传空字符串（必填）
    });
    if (result != null) {
      var response = ListResponse.fromJson(result);
      if (response.code == 1) {
        var records = response.data
            .map((e) => Comment.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 删除评论
  void _delete(int index) async {
    DialogUtils.showWaitDialog(context);
    // 判断是评论还是回复
    var data;
    if (_items[index].byRepliedId == null) {
      // 删除评论
      data = await XHttp.postJson(Urls.COMMENT_REMOVE, {
        "id": _items[index].id, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    } else {
      // 删除回复
      data = await XHttp.postJson(Urls.REPLY_REMOVE, {
        "id": _items[index].id, // 回复ID
        "commentId": _items[index].commentId, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    }
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        setState(() {
          _items.removeAt(index);
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
